package com.jds.test.httpproxy.miniserver;

import com.alibaba.fastjson.JSON;
import com.jds.test.httpproxy.httpclient.OriginHttp;
import com.jds.test.httpproxy.httpclient.ResHttp;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.*;

import java.util.List;
import java.util.Map;

/**
 * Created by sunyuming on 18/8/30.
 */
public class BodyToResponseEncoder extends MessageToMessageEncoder<ResHttp> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, ResHttp resHttp, List<Object> list) throws Exception {

        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.valueOf(resHttp.getRet()),
                Unpooled.wrappedBuffer(resHttp.getBody()));

        Map<String, String> headers = resHttp.getHeaders();
        for(Map.Entry<String, String> entry : headers.entrySet()) {
            response.headers().set(entry.getKey(), entry.getValue());
        }

        response.headers().remove("X-Frame-Options");

        /**
         * 对长连接，chunked与length要有其一但又不能共存，在postman上与chunked冲突
         */
        if(!response.headers().contains("Transfer-Encoding") && !"chunked".equals(response.headers().get("Transfer-Encoding")))
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
//        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
//
//        // 下面2个支持跨域
//        response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
//        response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS, HttpHeaders.Names.CONTENT_TYPE);

        list.add(response);
    }
}
